package com.guard.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.guard.R;
import com.guard.android.GuardAplication;
import com.guard.android.GuardManager;
import com.guard.helper.StringHelper;
import com.guard.location.UserData;
import com.guard.net.HttpConnectionError;

public class MainActivity extends AbstractActivity {

    // button sos -----start-----
    private ProgressBar progressBar;
    private ImageButton buttonSOS;
    // geocoder -----start-----
    private long timeoutDelay = 15000; // ms
    private Handler mHandler = new Handler();
    private ProgressDialog mDialogfetchGeoCoder;
    private AsyncTask<Void, Void, String> fetchGeoCoderTask;
    private Runnable cancelFetchGeoCoderTaskTasks = new Runnable() {
        public void run() {
            cancelfetchGeoCoderTask();
        }
    };

    // balance -----start-----
    private ProgressDialog mDialogfetchBalance;
    // -----all-----
    private UserData userData;
    private AutoCompleteTextView autoAdrressEditText;
    public static boolean isGPSDialogShowingNow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedKillApp) {
            isNeedKillApp = false;
            finish();
        } else {
            // userData = GuardAplication.instance().getUserData();
            // checkGpsStatus();
            checkBalanceStatus();
        }
    }
//
//    private void checkGpsStatus() {
//        if (!userData.checkLocationProvidersStatus() && !isGPSDialogShowingNow) {
//            try {
//                new EnableGpsDialogFragment().show(getSupportFragmentManager(), "enableGpsDialog");
//                isGPSDialogShowingNow = true;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    private void init() {
        userData = GuardAplication.instance().getUserData();
        autoAdrressEditText = (AutoCompleteTextView) findViewById(R.id.address_edit_text);
        fetchGeoCoderAdrress();
        initSOSButton();
    }

    // ----------------------sendSOS start-------------------------------------------
    private void initSOSButton() {
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        buttonSOS = (ImageButton) findViewById(R.id.button);
        buttonSOS.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (autoAdrressEditText.length() == 0 && autoAdrressEditText.isShown()) {
                    showToast(getResources().getString(R.string.enter_address));
                    return;
                } else {
                    userData.setUserAdrress(autoAdrressEditText.getText().toString());
                    sendSOS();
                }
            }
        });
    }

    private void sendSOS() {

        new AsyncTask<Void, Boolean, Integer>() {

            private Exception mException = null;

            protected void onPreExecute() {
                buttonSOS.setEnabled(false);
                buttonSOS.setClickable(false);
                progressBar.setVisibility(View.VISIBLE);
            };

            @Override
            protected Integer doInBackground(Void... params) {
                Integer result = -1;
                try {
                    result = GuardManager.instance().sendSOS();
                } catch (HttpConnectionError e) {
                    mException = e;
                }
                return result;
            }

            protected void onPostExecute(Integer result) {
                progressBar.setVisibility(View.GONE);
                buttonSOS.setEnabled(true);
                buttonSOS.setClickable(true);
                switch (result) {
                case -1: // response == null || response.isFailed()
                    showToast(getResources().getString(R.string.order_not_send));
                    break;
                case 0: // No cookie
                    showToast(getResources().getString(R.string.order_not_send));
                    startMyActivity(RegisterActivity.class);
                    break;
                case 1: // Ok
                    showToast(getResources().getString(R.string.order_send));
                    break;
                }
                if (mException != null) {
                    showConnectionErrorDialog();
                }
            };
        }.execute((Void) null);
    }

    // ----------------------sendSOS end--------------------------------------------
    // -----------------------------------------------------------------------------
    // ----------------------geocoder start-----------------------------------------
    private void cancelfetchGeoCoderTask() {
        mHandler.removeCallbacks(cancelFetchGeoCoderTaskTasks);
        if (fetchGeoCoderTask != null && fetchGeoCoderTask.getStatus() != Status.FINISHED) {
            System.out.println("OLEG: MainActivity.cancelfetchGeoCoderTask ");
            fetchGeoCoderTask.cancel(true);
            fetchGeoCoderTask = null;
            mDialogfetchGeoCoder.cancel();
            autoAdrressEditText.setText("");
            autoAdrressEditText.setHint(R.string.enter_address);
            String string = getString(R.string.geo_coder_error);
            showToast(string);
        }
    }

    public void fetchGeoCoderAdrress() {
        fetchGeoCoderTask = new AsyncTask<Void, Void, String>() {

            protected void onPreExecute() {

                mDialogfetchGeoCoder = getProgressDialog(getResources().getString(R.string.geo_coder_message), false);
                mDialogfetchGeoCoder.show();
                autoAdrressEditText.setHint(R.string.recieving_address);
                mHandler.postDelayed(cancelFetchGeoCoderTaskTasks, timeoutDelay);
            };

            private Exception mException = null;

            @Override
            protected String doInBackground(Void... params) {
                String data = null;
                int tryCount = 3;
                for (int i = 0; i < tryCount; i++) {
                    data = reqestAdress();
                    System.out.println("OLEG: doInBackground count = " + i + " data = " + data);
                    if (data != null && !data.equals("")) {
                        return data;
                    }
                    if (i != tryCount - 1) {
                        try {
                            System.out.println("OLEG: doInBackground sleep(1000)");
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                return data;
            }

            private String reqestAdress() {
                String result = null;
                try {
                    result = GuardManager.instance().getUserGeoCoder();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (result == null || result.equals("") || result.equals("-1") || result.length() > 30) {
                    try {
                        // -------------- Start google geoCoder --------------
                        System.out.println("OLEG: Start google geoCoder ");
                        List<Address> addressList = new ArrayList<Address>();
                        Geocoder geocoder = new Geocoder(getApplicationContext());
                        if (userData.getCurrentPosition() != null && userData.isLocationAccuracyValid()) {
                            double x = userData.getCurrentPosition().getLatitude();
                            double y = userData.getCurrentPosition().getLongitude();
                            addressList = geocoder.getFromLocation(x, y, 1);
                            Address address = addressList.get(0);
                            result = address.getAddressLine(0);
                        } else if (userData != null) {
                            System.out.println("OLEG: isLocationAccuracyValid" + userData.isLocationAccuracyValid());

                        }

                    } catch (IOException e) {
                        System.out.println("OLEG: MainActivity.fetchGeoCoderAdrress IOException" + e.getMessage());
                        e.printStackTrace();
                    } catch (HttpConnectionError e) {
                        mException = e;
                    }
                    // -------------- End google geoCoder --------------
                }
                return result;

            }

            @Override
            protected void onPostExecute(String result) {
                System.out.println("OLEG: onPostExecute result = " + result);
                if (result != null && !result.equals("")) {
                    autoAdrressEditText.setText(result);
                } else {
                    autoAdrressEditText.setText("");
                    autoAdrressEditText.setHint(R.string.enter_address);
                    String string = getString(R.string.geo_coder_error);
                    showToast(string);
                }
                if (mException != null) {
                    showConnectionErrorDialog();
                }
                mDialogfetchGeoCoder.dismiss();
            }
        }.execute();
    }

    // ----------------------geocoder end-------------------------------------------
    // -----------------------------------------------------------------------------
    // ----------------------checkBalance start-------------------------------------
    public void checkBalanceStatus() {
        new AsyncTask<Void, Void, String>() {

            protected void onPreExecute() {
                mDialogfetchBalance = getProgressDialog(getString(R.string.check_balance_message_text), false);
                mDialogfetchBalance.show();
            };

            @Override
            protected String doInBackground(Void... params) {
                String balance = null;
                int tryCount = 3;
                for (int i = 0; i < tryCount; i++) {
                    balance = reqestBalance();
                    System.out.println("OLEG: doInBackground count = " + i + " data = " + balance);
                    if (balance != null && !balance.equals("")) {
                        return balance;
                    }
                    if (i != tryCount - 1) {
                        try {
                            System.out.println("OLEG: doInBackground sleep(1000)");
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                return balance;
            }

            private String reqestBalance() {
                String result = null;
                try {
                    result = GuardManager.instance().checkBalance();
                } catch (HttpConnectionError e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                mDialogfetchBalance.dismiss();
                System.out.println("OLEG: onPostExecute balance = " + result);
                if (result != null && !result.equals("")) {
                    List<String> lines = StringHelper.getLinesList(result);
                    if (lines.get(0).equalsIgnoreCase("No cookie")) {
                        startMyActivity(RegisterActivity.class);
                    } else if (lines.get(0).equalsIgnoreCase("Ok")) {
                        String cookie = GuardManager.instance().getCookie();
                        if (cookie == null || cookie.isEmpty()) {
                            startMyActivity(RegisterActivity.class);
                        } else {
                            init();
                        }
                    } else if (lines.get(0).equalsIgnoreCase("No money")) {
                        startMyActivity(PaymentWebViewActivity.class);
                    }
                } else {
                    showConnectionErrorDialog();
                }
            }
        }.execute();
    }

    private void startMyActivity(Class<?> cls) {
        Intent myIntent = new Intent(getApplicationContext(), cls);
        // myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(myIntent);
    }
}
